import tkinter as tk
from tkinter import messagebox
import random

# 假名到罗马音映射表
KANA_TO_ROMAJI = {
    # 平假名
    'あ':'a',  'い':'i',  'う':'u',  'え':'e',  'お':'o',
    'か':'ka', 'き':'ki', 'く':'ku', 'け':'ke', 'こ':'ko',
    'さ':'sa', 'し':'shi','す':'su', 'せ':'se', 'そ':'so',
    'た':'ta', 'ち':'chi','つ':'tsu','て':'te', 'と':'to',
    'な':'na', 'に':'ni', 'ぬ':'nu', 'ね':'ne', 'の':'no',
    'は':'ha', 'ひ':'hi', 'ふ':'fu', 'へ':'he', 'ほ':'ho',
    'ま':'ma', 'み':'mi', 'む':'mu', 'め':'me', 'も':'mo',
    'や':'ya', 'ゆ':'yu', 'よ':'yo',
    'ら':'ra', 'り':'ri', 'る':'ru', 'れ':'re', 'ろ':'ro',
    'わ':'wa', 'を':'o',  'ん':'n',
    # 片假名 
    'ア':'a',  'イ':'i',  'ウ':'u',  'エ':'e',  'オ':'o',
    'カ':'ka', 'キ':'ki', 'ク':'ku', 'ケ':'ke', 'コ':'ko',
    'サ':'sa', 'シ':'shi','ス':'su', 'セ':'se', 'ソ':'so',
    'タ':'ta', 'チ':'chi','ツ':'tsu','テ':'te', 'ト':'to',
    'ナ':'na', 'ニ':'ni', 'ヌ':'nu', 'ネ':'ne', 'ノ':'no',
    'ハ':'ha', 'ヒ':'hi', 'フ':'fu', 'ヘ':'he', 'ホ':'ho',
    'マ':'ma', 'ミ':'mi', 'ム':'mu', 'メ':'me', 'モ':'mo',
    'ヤ':'ya', 'ユ':'yu', 'ヨ':'yo',
    'ラ':'ra', 'リ':'ri', 'ル':'ru', 'レ':'re', 'ロ':'ro',
    'ワ':'wa', 'ヲ':'o',  'ン':'n'
}

class UniqueKanaQuiz:
    def __init__(self, master):
        self.master = master
        self.master.title("唯一假名测验")
        self.level = 1
        self.target_romaji = None
        self.correct_kana = None
        self.buttons = []
        
        # 界面布局
        self.header = tk.Label(master, text="", font=('Arial', 24))
        self.header.pack(pady=20)
        
        self.grid_frame = tk.Frame(master)
        self.grid_frame.pack()
        
        self.start_new_round()

    def generate_distractors(self):
        """生成不重复的干扰项假名"""
        consonant = self.target_romaji[0] if len(self.target_romaji) > 1 else ''
        
        # 第一阶段：收集相同辅音的假名
        same_consonant = [
            k for k, r in KANA_TO_ROMAJI.items()
            if r.startswith(consonant) 
            and k != self.correct_kana
        ]
        
        # 第二阶段：收集其他假名
        other_kanas = [
            k for k, r in KANA_TO_ROMAJI.items()
            if not r.startswith(consonant)
            and k != self.correct_kana
        ]
        
        # 合并并随机选择
        combined = same_consonant + other_kanas
        random.shuffle(combined)
        
        # 确保最终返回8个唯一假名
        return list(dict.fromkeys(combined))[:8]  # 保留顺序的去重方式

    def start_new_round(self):
        # 生成新题目
        self.target_romaji, self.correct_kana = random.choice(
            [(r, k) for k, r in KANA_TO_ROMAJI.items()]
        )
        self.header.config(text=f"找出对应发音：{self.target_romaji}")
        
        # 生成唯一假名集合
        all_kanas = [self.correct_kana] + self.generate_distractors()
        while len(all_kanas) < 9:  # 防止极端情况重复
            all_kanas += [k for k in KANA_TO_ROMAJI if k not in all_kanas]
        random.shuffle(all_kanas)
        
        # 创建3x3网格
        for i in range(9):
            row, col = divmod(i, 3)
            kana = all_kanas[i]
            
            btn = tk.Button(
                self.grid_frame,
                text=kana,
                font=('MS Gothic', 22),
                width=3,
                height=1,
                command=lambda k=kana: self.check_answer(k)
            )
            btn.grid(row=row, column=col, padx=5, pady=5)
            self.buttons.append(btn)

    def check_answer(self, selected_kana):
        if selected_kana == self.correct_kana:
            self.level += 1
            msg = f"正确！进入第 {self.level} 关"
            messagebox.showinfo("结果", msg)
            self.clear_grid()
            self.start_new_round()
        else:
            correct_romaji = KANA_TO_ROMAJI[self.correct_kana]
            msg = f"错误！{selected_kana} 的发音是 {KANA_TO_ROMAJI[selected_kana]}\n正确答案：{self.correct_kana} ({correct_romaji})"
            messagebox.showinfo("结果", msg)
            self.level = max(1, self.level-1)
            self.clear_grid()
            self.start_new_round()

    def clear_grid(self):
        for btn in self.buttons:
            btn.destroy()
        self.buttons = []

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("550x600")
    quiz = UniqueKanaQuiz(root)
    root.mainloop()